package com.common.utils;

import com.common.global.BizException;
import com.common.global.BizServiceEnum;
import com.common.global.CommonEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author johnny
 * @create 2021-05-16 1:23 下午
 **/
@Slf4j
public class UploadUtils {

    public static String uploadImage(MultipartFile file, String filePath, String accessPrefix) {
        // 文件名
        String fileName = file.getOriginalFilename();
        if (StringUtils.isEmpty(fileName)) {
            throw new BizException(BizServiceEnum.UPLOAD_NO_FILE_NAME);
        } else {
            // 后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID() + suffixName;
        }
        // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new BizException(CommonEnum.FILE_UPLOAD_FAIL.getResultCode(), CommonEnum.FILE_UPLOAD_FAIL.getResultMsg() + "e:" + e.getMessage());
        }
        log.info("【upload  Path : {}】", filePath + fileName);
        //String path = "/Users/johnny/Downloads/upimage/" + fileName;
        return accessPrefix + fileName;
    }

}